package aliyun.oss.finalwork02.utils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class StatisticsUtil {

    public static Long timeStatistics(Object o, String methodName, Class<?>[] parameterTypes, Object... args) {
        try {
            Method method = o.getClass().getMethod(methodName, parameterTypes);
            long startTime = System.nanoTime(); // 获取开始时间
            method.invoke(o, args); // 调用方法
            long endTime = System.nanoTime(); // 获取结束时间
            return endTime - startTime; // 返回方法执行时间（纳秒）
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        // 示例使用
        ExampleClass example = new ExampleClass();
        Long timeTaken = StatisticsUtil.timeStatistics(example, "exampleMethod", new Class<?>[]{String.class}, "test");
        if (timeTaken != null) {
            System.out.println("Method execution time: " + timeTaken + " nanoseconds");
        } else {
            System.out.println("Method execution failed.");
        }
    }
}

class ExampleClass {
    public void exampleMethod(String input) {
        // 模拟耗时操作
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Executed method with input: " + input);
    }
}
